use ane_cms::dao::Manager as CmsManager;
use ane_cms::dao::{ArticleDetailVo, ArticleDo, ArticleListVo};
use axum::{
    extract::{Path, Query, State},
    response::IntoResponse,
    Extension,
};
use common::page::{PageInfo, PageParams};

use crate::{
    error::AppResult,
    extract::{Json, ValJson},
    state::ShareState,
};

pub async fn list(
    State(state): State<ShareState>,
    Query(page_params): Query<PageParams>,
) -> AppResult<impl IntoResponse> {
    CmsManager::list_article::<ArticleListVo>(
        state.db(),
        page_params.page - 1,
        page_params.page_size,
        0,
        None,
        None,
    )
    .await
    .map(|(total, datas)| PageInfo::new(datas, &page_params, total))
    .map(Json)
    .map_err(Into::into)
}

pub async fn fetch_article(
    State(state): State<ShareState>,
    Path(id): Path<i32>,
) -> AppResult<impl IntoResponse> {
    CmsManager::fetct_article::<ArticleDetailVo>(state.db(), 0, id)
        .await
        .map(Json)
        .map_err(Into::into)
}

pub async fn create_article(
    State(state): State<ShareState>,
    ValJson(data): ValJson<ArticleDo>,
) -> AppResult<impl IntoResponse> {
    CmsManager::create_article(state.db(), 0, data)
        .await
        .map(Json)
        .map_err(Into::into)
}

pub async fn update_article(
    State(state): State<ShareState>,
    Path(id): Path<i32>,
    ValJson(data): ValJson<ArticleDo>,
) -> AppResult<impl IntoResponse> {
    CmsManager::update_article(state.db(), 0, id, data)
        .await
        .map(Json)
        .map_err(Into::into)
}

pub async fn delete_article(
    State(state): State<ShareState>,
    Path(id): Path<i32>,
) -> AppResult<impl IntoResponse> {
    ane_cms::dao::Manager::del_article(state.db(), 0, id)
        .await
        .map(Json)
        .map_err(Into::into)
}
